package com.situ.fly.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.fly.entity.Answer;
import com.situ.fly.entity.Question;
import com.situ.fly.entity.User;
import com.situ.fly.mapper.AnswerMapper;
import com.situ.fly.mapper.LikeMapper;
import com.situ.fly.mapper.QuestionMapper;
import com.situ.fly.mapper.UserMapper;
import com.situ.fly.service.AnswerService;

@Service
public class AnswerServiceImpl implements AnswerService {

	@Autowired
	private AnswerMapper answerMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private QuestionMapper questionMapper;
	@Autowired
	private LikeMapper likeMapper;
	
	@Override
	public int add(Answer answer) {
		return answerMapper.insert(answer);
	}

	@Override
	public List getByQid(Integer qid, Integer uid) {
		return answerMapper.selectByQid(qid, uid);
	}

	@Override
	public List getByUid(Integer uid) {
		return answerMapper.selectByUid(uid);
	}

	@Override
	public Answer getById(Integer id) {
		return answerMapper.selectById(id);
	}

	@Override
	public int edit(Answer answer) {
		return answerMapper.update(answer);
	}

	@Override
	public int delete(Answer answer) {
		answer.setStatus(2);
		
		return answerMapper.update(answer);
	}

	@Override
	public int accept(Answer answer) {

		answer = answerMapper.selectById(answer.getId());
		Question question = questionMapper.selectById(answer.getQid());
		User auth = userMapper.selectById(question.getUid());
		User user = userMapper.selectById(answer.getUid());
		
		// 需要扣分
		if (auth.getKiss() < question.getKiss()) {
			return -1;
		}
		
		auth.setKiss(auth.getKiss()-question.getKiss());
		userMapper.update(auth);
		
		user.setKiss(user.getKiss()+question.getKiss());
		userMapper.update(user);
		
		// 需要修改成结帖
		question.setStatus(1);
		questionMapper.update(question);
		
		answer.setStatus(1);
		
		return answerMapper.update(answer);
	}

	@Override
	public int like(Integer id, Integer uid, Boolean ok) {
		
		if (ok) {
			// 取消点赞
			likeMapper.delete(id, uid);
		} else {
			// 点赞
			likeMapper.insert(id, uid);
		}
		
		return 1;
	}

}
